package com.leilei.serviceProject.domain.strategy.service.rule.chain.factory;

import com.leilei.serviceProject.domain.strategy.model.entity.StrategyEntity;
import com.leilei.serviceProject.domain.strategy.repository.IStrategyRepository;
import com.leilei.serviceProject.domain.strategy.service.rule.chain.ILogicChain;
import com.leilei.serviceProject.types.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author yanglei
 * @description 责任链工厂
 * @create 2024/11/13 15:16
 */
@Service
public class DefaultLogicChainFactory {
    private final Map<String, ILogicChain> logicChainMap;
    private final IStrategyRepository strategyRepository;

    public DefaultLogicChainFactory(Map<String, ILogicChain> logicChainMap, IStrategyRepository strategyRepository) {
        this.logicChainMap = logicChainMap;
        this.strategyRepository = strategyRepository;
    }

    /**
     * @description 构建责任链
     * @param
     * @return 责任链对象
     */
    public ILogicChain openLogicChain(Long strategyId) {
        StrategyEntity strategyEntity = strategyRepository.queryStrategyEntityByStrategyId(strategyId);
        if (StringUtils.isBlank(strategyEntity.getRuleModels())) {
            return logicChainMap.get("default");
        }

        String[] ruleModelArray = strategyEntity.getRuleModels().split(Constants.SPLIT);
        ILogicChain logicChain = logicChainMap.get(ruleModelArray[0]);
        ILogicChain currentChain = logicChain;
        for (int i = 1; i < ruleModelArray.length; i++) {
            currentChain = currentChain.appendNext(logicChainMap.get(ruleModelArray[i]));
        }

        currentChain.appendNext(logicChainMap.get("default"));
        return logicChain;
    }
}
